<script setup>
import axios from "axios";

async function asyncA() {
    let status = null;
    await axios.get("https://wkbrs1.tingyun.com/action").then((res) => {
        console.log(res.data);
        status = res.data.status;
    });
    return status;
}

async function test() {
    let v = await asyncA();
    console.log(v);
}

function run(func) {
    let cache = {
        status: "pending",
        value: null,
    };
    const oldFetch = window.fetch;
    window.fetch = function (...args) {
        if (cache.status == "fulfilled") {
            return cache.value;
        } else if (cache.status == "rejected") {
            //之前的请求有问题
            throw cache.value;
        } else {
            // 1. 发送真是请求
            const promise = oldFetch(...args).then(
                (res) => {
                    console.log(111, res);
                    cache.status = "fulfilled";
                    cache.value = res;
                },
                (err) => {
                    cache.status = "rejected";
                    cache.value = err;
                }
            );
            // 2. 抛出错误
            throw promise;
        }
    };
    // 执行入口函数
    try {
        func();
    } catch (error) {
        if (error instanceof Promise) {
            // 不论成功还是失败都重新调用
            error.then(func, func).finally(() => {
                console.log(222);
                //恢复原来的值
                window.fetch = oldFetch;
            });
        }
    }
}

function getUser() {
    return fetch("https://wkbrs1.tingyun.com/action");
}

function m1() {
    const user = getUser();
    return user;
}

function m2() {
    const user = m1();
    return user;
}
function m3() {
    const user = m2();
    return user;
}

function main() {
    console.log("start");
    const user = m3();
    console.log("end");

    user.json().then((res) => {
        console.log(res);
    });
}
run(main);
</script>

<template>
    <div>test</div>
</template>
